#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#include <stdlib.h>
#define High 20
#define Width 40


//全局变量
int length;  // 舍身长度
int head_x, head_y; // 舌头位置
int dd_x, dd_y;
int body_x[100], body_y[100];
char direct;
int speed;


void gotoxy(int x,int y)  //光标移动到(x,y)位置
{
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    pos.X = x;
    pos.Y = y;
    SetConsoleCursorPosition(handle,pos);
}

void HideCursor() // 用于隐藏光标
{
	CONSOLE_CURSOR_INFO cursor_info = {1, 0};  // 第二个值为0表示隐藏光标
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

void start(){
	srand((unsigned)time(NULL));
	head_x = Width / 2;
	head_y = High / 2;
	length =  3;
	dd_x = rand() % (Width - 1) + 1;
	dd_y = rand() % (High - 1) + 1;
	body_x[1] = head_x - 1;
	body_y[1] = head_y;
	body_x[2] = head_x - 2;
	body_y[2] = head_y;
	body_x[3] = head_x - 3;
	body_y[3] = head_y;
	direct = 'd';
	speed = 0;

	HideCursor(); // 隐藏光标
}

void user(){
	char input;
	if(kbhit())  // 判断是否有输入
	{
		input = getch();  // 根据用户的不同输入来移动，不必输入回车	
		if (input == 'w')
			direct = 'w';
		if (input == 's')
			direct = 's';
		if (input == 'd')
			direct = 'd';
		if (input == 'a')
			direct = 'a';



	}

}

void update(){
	int i;
	speed ++;
	if (speed == 20){
		if (direct == 'd'){
			head_x++;
			for (i = 1; i <= length; i ++){
			body_x[i] ++;
			}
		}

		if (direct == 'a'){
			head_x--;
			for (i = 1; i <= length; i ++){
			body_x[i] --;
			}
		}
		if (direct == 's'){
			head_y++;
			for (i = 1; i <= length; i ++){
			body_y[i] ++;
			}
		}
		if (direct == 'w'){
			head_y--;
			for (i = 1; i <= length; i ++){
			body_y[i] --;
			}
		}

		speed = 0;
	}




}

void show(){
	gotoxy(0,0);  // 光标移动到原点位置，以下重画清屏

	int i, j;
	int k;
	int p = 0;
	for (i = 1; i <= High; i ++){
		for (j = 1; j <= Width; j ++){
			for (k = 1; k <= length; k ++){
				if (i == body_y[k] && j == body_x[k]){
					printf ("o");
					p = 1;
				}
			}
			if (p == 0){
				if (i == head_y && j == head_x)     // 打印舌头
					printf ("@");
				else if (i == 1 || i == High)
					printf ("#");                   //打印边界
				else if (j == 1 || j == Width)
					printf ("#");                   //打印边界
				else if (i == dd_y && j == dd_x)
					printf ("$");
				
				else
					printf (" ");
			}
			p = 0;
		}
		printf ("\n");
	}

}

int main(){
	start();
	while(1){
		user();
		update();
		show();
	}
	return 0;
}
